package net.uhuijia.utils;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.params.CookiePolicy;

import java.io.IOException;
import java.net.ConnectException;
import java.net.UnknownHostException;

public class HttpClientHelper {
    private static final Log logger = LogFactory.getLog(HttpClientHelper.class);
    private static final String USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.16) Gecko/20110319 BTRS96900 Firefox/3.6.16";

    public static String getSourceByUrl(final String url) {
        HttpClient httpClient = new HttpClient();
        String str = null;
        PostMethod getMethod = new PostMethod(url);
        getMethod.setRequestHeader("User-Agent", USER_AGENT);
        getMethod.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 0);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(0);
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + getMethod.getStatusLine());
            }
            //str = IOUtils.toString(getMethod.getResponseBodyAsStream(), "UTF-8");
            str = getMethod.getResponseBodyAsString();
        } catch (UnknownHostException e) {
            logger.error("UnknownHostException: Please check your provided http address!");
        } catch (HttpException e) {
            logger.error("HttpException: Please check your provided http address!");
        } catch (ConnectException e) {
            logger.error("IOException: Please check your provided http address!");
        } catch (IOException e) {
            logger.error("IOException: Please check your provided http address!");
        } finally {
            getMethod.releaseConnection();
        }
        return str;
    }

    /**
     * POST请求
     * @param url url地址
     * @param params 参数
     * @return
     */
    public static String post(String url, NameValuePair[] params) {
        HttpClient httpClient = new HttpClient();
        String str = null;
        PostMethod getMethod = new PostMethod(url);
        getMethod.setRequestHeader("User-Agent", USER_AGENT);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        if (params != null) {
            getMethod.addParameters(params);
        }
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + getMethod.getStatusLine() + ",url:[" + url + "]");
            }
            str = getMethod.getResponseBodyAsString();
        } catch (Exception e) {
            logger.error("HttpClientUtil post error.url:[" + url + "]", e);
        } finally {
            getMethod.releaseConnection();
        }
        return str;
    }

    public static String get(String url) {
        HttpClient httpClient = new HttpClient();
        String str = null;
        GetMethod getMethod = new GetMethod(url);
        getMethod.setRequestHeader("User-Agent", USER_AGENT);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + getMethod.getStatusLine() + ",url:[" + url + "]");
            }
            str = getMethod.getResponseBodyAsString();
        } catch (Exception e) {
            logger.error("HttpClientUtil get error.url:[" + url + "]", e);
        } finally {
            getMethod.releaseConnection();
        }
        return str;
    }
}
